<?php

namespace App\Http\Controllers\V1\API;

use App\Models\V1\AdminUser;
use App\Models\V1\Custodians;
use App\Models\V1\NewStudent;
use App\Models\V1\School;
use App\Models\V1\Professional;
use App\Models\V1\Major;
use App\Models\V1\OAuthClients;
use App\Models\V1\WeChatLogin;
use GuzzleHttp\Client;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Storage;
use Auth;
use Log;
use Validator;
use App\Http\Controllers\V1\API\BaseController;
use Illuminate\Support\Facades\DB;

class NewStudentsController extends BaseController
{
    /*
     * 分页获取新生列表
     */
    public function getNewStudentList(Request $request)
    {
        // 自定义返回格式
        $result = array(
            'errorCode' => Response::HTTP_BAD_REQUEST,
            'errorMsg' => Response::$statusTexts[Response::HTTP_BAD_REQUEST],
            'data' => array()
        );
        // 获取所有请求参数
        $reqParams = $request->all();
        //验证请求参数
        $validator = $this->validateGetNewStudentRequest($reqParams);
        if ($validator->fails()) {
            $result['errorMsg'] = $validator->error()->all()[0];
            return $this->sendResponse($result, $result['errorCode']);
        }
        $resultData = $this->getNewStudentListData($reqParams);
        //格式化数据
        $NewStudentDataList = array(
            'total' => $resultData->total(),
            'currentPage' => $resultData->currentPage(),
            'lastPage' => $resultData->lastPage(),
            'perPage' => $resultData->perPage(),
            'dataList' => array()
        );
        // 数据迭代&格式化
        if ($resultData == '[]') {
            $result['errorCode'] = Response::HTTP_OK;
            $result['errorMsg'] = '无数据';
            $result['data'] = $NewStudentDataList;
        } else {
            $formatlist = array();
            //格式化数据

            foreach ($resultData->items() as $item) {

                $formatlist['arrivalCode'] = $item->arrival_code;
                $formatlist['enrollmentNumbering'] = $item->enrollment_numbering;
                $formatlist['examCode'] = $item->exam_code;
                $formatlist['name'] = $item->name;
                $formatlist['sex'] = $item->sex;
                $formatlist['avatar'] = $item->avatar;
                $formatlist['mobile'] = $item->mobile;
                $formatlist['address'] = $item->address;
                $formatlist['cardType'] = $item->card_type;
                $formatlist['cardNumber'] = $item->card_number;
                $formatlist['birthday'] = $item->birthday;
                $formatlist['originalType'] = $item->original_type;
                $formatlist['admissionProperty'] = $item->admission_property;
                $formatlist['employmentType'] = $item->employment_type;
                $formatlist['examProvince'] = $item->exam_province;
                $formatlist['examArea'] = $item->exam_area;
                $formatlist['graduatedSchool'] = $item->graduated_school;
                $formatlist['schoolType'] = $item->school_type;
                $formatlist['enrollmentType'] = $item->enrollment_type;
                $formatlist['score'] = $item->score;
                $formatlist['politicalStatus'] = $item->political_status;
                $formatlist['height'] = $item->height;
                $formatlist['weight'] = $item->weight;
                $formatlist['bodyType'] = $item->body_type;
                $formatlist['physicalFitness'] = $item->physical_fitness;
                $formatlist['medicalHistory'] = $item->medical_history;
                $formatlist['bloodType'] = $item->blood_type;
                $formatlist['illRemark'] = $item->ill_remark;
                $formatlist['enrollmentCategory'] = $item->enrollment_category;
                $formatlist['enrollmentCode'] = $item->enrollment_code;
                $formatlist['enrollmentDirectory'] = $item->enrollment_directory;
                $formatlist['majorDirectoryCode'] = $item->major_directory_code;
                $formatlist['academicCategory'] = $item->academic_category;
                $formatlist['readYear'] = $item->read_year;
                $formatlist['schoolMode'] = $item->school_mode;
                $formatlist['ethnic'] = $item->ethnic;
                $formatlist['household'] = $item->household;
                $formatlist['supportType'] = $item->support_type;
                $formatlist['payStatus'] = $item->pay_status;
                $formatlist['reportStatus'] = $item->report_status;
                $formatlist['isStay'] = $item->is_stay;
                $formatlist['classCode'] = $item->class_code;
                $formatlist['dormCode'] = $item->dorm_code;
                $formatlist['textbookStatus'] = $item->textbook_status;
                $formatlist['dailyUseStatus'] = $item->daily_use_status;
                $formatlist['keyStatus'] = $item->key_status;
                $formatlist['custodianTitle'] = $item->custodian_title;
                $formatlist['custodianName'] = $item->custodian_name;
                $formatlist['custodianMobile'] = $item->custodian_mobile;
                $formatlist['enrollmentTeacher'] = $item->enrollment_teacher;
                $formatlist['remark'] = $item->remark;
                $formatlist['graduatedClass'] = $item->graduated_class;
                $formatlist['enrollCategory'] = $item->enroll_category;
                $formatlist['enrollProfessional'] = $item->enroll_professional;
                $formatlist['parentsName'] = $item->parents_name;

                $data[] = $formatlist;
            }
            $NewStudentDataList['dataList'] = $data;

            $result['data'] = $NewStudentDataList;
            $result['errorCode'] = Response::HTTP_OK;
            $result['errorMsg'] = '数据获取成功';
        }
        return $this->sendResponse($result, $result['errorCode']);
    }

    /***
     * 验证分页获取新生列表接口
     */
    protected function validateGetNewStudentRequest(array $param)
    {

        $customRules = array(
            'page' => 'bail|required|integer',
            'limit' => 'bail|required|integer',
        );
        $customMessages = array(
            'page.required' => '当前页码不能为空',
            'page.integer' => '当前页码必须为整形数字',
            'limit.required' => '单页条数不能为空',
            'limit.integer' => '单页条数必须为整形数字',
        );
        return $this->validateRequest($param, $customRules, $customMessages);
    }

    /*
     * 获取新生列表数据接口
     */
    function getNewStudentListData(array $param)
    {
        $page = !empty($param['page']) ? $param['page'] : 1;
        $limit = !empty($param['limit']) ? $param['limit'] : 10;

        $result = NewStudent::orderBy('created_at', 'desc')
            ->paginate($limit, ['*'], 'page', $page);

        return $result;
    }


    /*
     * 获取新生基本信息
     */
    public function getNewStudentInformation(Request $request)
    {
        // 自定义返回格式
        $result = array(
            'errorCode' => Response::HTTP_BAD_REQUEST,
            'errorMsg' => Response::$statusTexts[Response::HTTP_BAD_REQUEST],
            'data' => array()
        );
        // 获取所有请求参数
        $reqParams = $request->all();
        //获取登录ID
        $exam_code = $reqParams['userID'];

        // 获取登录新生基本信息
        $resultData = NewStudent::where('exam_code', $exam_code)->first();

        // 获取需要字段信息
        $dataList['graduatedSchool'] = $resultData->graduated_school;   // 毕业学校
        $dataList['graduatedClass'] = $resultData->graduated_class;   // 毕业学校的初三班级
        $dataList['enrollCategory'] = $resultData->enroll_category;   // 报考类别
        $dataList['enrollProfessional'] = $resultData->enroll_professional;   // 报考专业
        $dataList['parentsName'] = $resultData->parents_name;   // 家长姓名
        $dataList['parentsMobile'] = Custodians::where(['exam_code' => $exam_code, 'custodian_name' => $request->parents_name])->value('custodian_mobile');  //监护人电话
        $dataList['isStay'] = $resultData->is_stay;   // 是否住宿
        $dataList['score'] = $resultData->score;   // 成绩
        $dataList['mobile'] = $resultData->mobile;   // 手机号
        $dataList['sex'] = $resultData->sex;   // 性别
        $dataList['avatar'] = $resultData->avatar;   // 上传个人照片
        $dataList['address'] = $resultData->address;   // 家庭住址
        $dataList['enrollmentTeacher'] = $resultData->enrollment_teacher;   // 招生代表
        // 数据迭代&格式化
        if ($resultData == '[]') {
            $result['errorCode'] = Response::HTTP_OK;
            $result['errorMsg'] = '无数据';
            $result['data'] = array();
        } else {
            $result['data'] = $dataList;
            $result['errorCode'] = Response::HTTP_OK;
            $result['errorMsg'] = '数据获取成功';
        }
        return $this->sendResponse($result, $result['errorCode']);
    }

    /*
     * 更新新生个人信息
     */
    public function editNewStudentInformation(Request $request)
    {
        // 自定义返回格式
        $result = array(
            'errorCode' => Response::HTTP_BAD_REQUEST,
            'errorMsg' => Response::$statusTexts[Response::HTTP_BAD_REQUEST],
            'data' => array()
        );
        // 获取所有请求参数
        $reqParams = $request->all();

        // 更新信息
        $successFlag = $this->handleUpdate($reqParams);
        if ($successFlag) {
            $result['errorMsg'] = '数据更新成功';
            $result['errorCode'] = Response::HTTP_OK;
        } else {
            $result['errorMsg'] = '数据更新失败';
            $result['errorCode'] = Response::HTTP_BAD_REQUEST;
        }
        return $this->sendResponse($result, $result['errorCode']);
    }

    public function handleUpdate(array $params)
    {
        $rspObj = false;
        DB::beginTransaction();
        try {
            $userID = $params['userID']; // 获取新生用户ID
            if (key_exists('graduatedSchool', $params)) {
                NewStudent::where('exam_code', $userID)->update([
                    'graduated_school' => $params['graduatedSchool']
                ]);
            }
            if (key_exists('graduatedClass', $params)) {
                NewStudent::where('exam_code', $userID)->update([
                    'graduated_class' => $params['graduatedClass']
                ]);
            }
            if (key_exists('enrollCategory', $params)) {
                NewStudent::where('exam_code', $userID)->update([
                    'enroll_category' => $params['enrollCategory']
                ]);
            }
            if (key_exists('enrollProfessional', $params)) {
                NewStudent::where('exam_code', $userID)->update([
                    'enroll_professional' => $params['enrollProfessional']
                ]);
            }
            if (key_exists('parentsName', $params)) {
                NewStudent::where('exam_code', $userID)->update([
                    'parents_name' => $params['parentsName']
                ]);
            }
            if (key_exists('isStay', $params)) {
                NewStudent::where('exam_code', $userID)->update([
                    'is_stay' => $params['isStay']
                ]);
            }
            if (key_exists('score', $params)) {
                NewStudent::where('exam_code', $userID)->update([
                    'score' => $params['score']
                ]);
            }
            if (key_exists('mobile', $params)) {
                NewStudent::where('exam_code', $userID)->update([
                    'mobile' => $params['mobile']
                ]);
            }
            if (key_exists('sex', $params)) {
                NewStudent::where('exam_code', $userID)->update([
                    'sex' => $params['sex']
                ]);
            }
            if (key_exists('avatar', $params)) {
                NewStudent::where('exam_code', $userID)->update([
                    'avatar' => $params['avatar']
                ]);
            }
            if (key_exists('address', $params)) {
                NewStudent::where('exam_code', $userID)->update([
                    'address' => $params['address']
                ]);
            }
            if (key_exists('enrollmentTeacher', $params)) {
                NewStudent::where('exam_code', $userID)->update([
                    'enrollment_teacher' => $params['enrollmentTeacher']
                ]);
            }
            DB::commit();
            $rspObj = true;
        } catch (\Exception $e) {
            DB::rollback();
        }
        return $rspObj;
    }

    /***
     * 根据省,市获取学校接口
     *
     */
    function selectCitySchool()
    {
        //自定义返回格式
        $result = array(
            'errorCode' => Response::HTTP_BAD_REQUEST,
            'errorMsg' => Response::$statusTexts[Response::HTTP_BAD_REQUEST],
            'data' => array()
        );

        $resultData = School::get();
        //将数据表中存在的所有省份,城市存到相应数组
        for ($i = 0; $i < count($resultData); $i++) {
            $province[$i] = $resultData[$i]->province;
        }
        for ($i = 0; $i < count($resultData); $i++) {
            $city[$i] = $resultData[$i]->city;
        }
        //唯一筛选数据中省份,城市的唯一性
        $provinceData = array();
        for ($i = 0; $i < count($province); $i++) {
            $a = 0;
            for ($k = 0; $k < count($provinceData); $k++) {
                if ($province[$i] == $provinceData[$k]) {
                    $a = 1;
                }
            }
            if ($a == 0) {
                $provinceData[] = $province[$i];
            }
        }
        $cityData = array();
        for ($i = 0; $i < count($city); $i++) {
            $b = 0;
            for ($k = 0; $k < count($cityData); $k++) {
                if ($city[$i] == $cityData[$k]) {
                    $b = 1;
                }
            }
            if ($b == 0) {
                $cityData[] = $city[$i];
            }
        }
        //$provinceData中存放省份列表
        //$cityData中存放城市列表
        for ($i = 0; $i < count($resultData); $i++) {
            //将学校放进对应的城市, 再将城市数组放进对应省份
            for ($v = 0; $v < count($cityData); $v++) {
                if ($resultData[$i]->city == $cityData[$v]) {
                    $data[$cityData[$v]][] = $resultData[$i]->name;
                }
                //将对应城市放进对应省份下面
                for ($m = 0; $m < count($provinceData); $m++) {
                    if ($resultData[$i]->province == $provinceData[$m]) {
                        $dataList[$provinceData[$m]] = $data;
                    }
                }
            }
        }

        $result['data'] = $dataList;
        $result['errorCode'] = Response::HTTP_OK;
        $result['errorMsg'] = '数据获取成功';

        return $this->sendResponse($result, $result['errorCode']);
    }

    /***
     * 专业选择
     */
    function selectProfessional()
    {
        //自定义返回格式
        $result = array(
            'errorCode' => Response::HTTP_BAD_REQUEST,
            'errorMsg' => Response::$statusTexts[Response::HTTP_BAD_REQUEST],
            'data' => array()
        );

        $resultData = Major::get();
        for ($i = 0; $i < count($resultData); $i++) {
//            $data[$resultData[$i]->code] = $resultData[$i]->name;
            $data[$i]['code'] = $resultData[$i]->code;
            $data[$i]['name'] = $resultData[$i]->name;
        }

        $result['data'] = $data;
        $result['errorCode'] = Response::HTTP_OK;
        $result['errorMsg'] = '数据获取成功';

        return $this->sendResponse($result, $result['errorCode']);
    }

}